/**
 * <p>Title: AuthoritySvc</p>
 * <p>Description: The Implement of Authority Svc</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2016</p>
 * <p>Company: Baosight Software</p>
 * @author Huang Zhongwei Chen Wei
 * @version 1.0
 * <pre>Histroy:
 *       2016-10-8  Huang Zhongwei  Create
 *</pre>
*/
package cn.jhg.account.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import cn.jhg.account.entity.AuditTrailObject;
import cn.jhg.account.entity.AuditTrailRecord;
import cn.jhg.account.entity.AuditTrailType;
import cn.jhg.account.entity.SignatureDefinition;
import cn.jhg.account.entity.User;
import cn.jhg.account.persist.SignatureDefinitionDao;
import cn.jhg.account.persist.UserDao;
import cn.jhg.account.service.AuditTrailSvc;
import cn.jhg.account.service.UserSvc;
import cn.jhg.account.util.SequenceProducer;
import cn.jhg.account.util.ServiceResult;
@Transactional
@Service("signatureSvc")
public class SignatureSvcImpl implements SignatureSvc {

	@Resource
	private SignatureDefinitionDao signatureDefinitionDao;
	@Resource
	private SequenceProducer sequenceProducer;
	@Resource
	private AuditTrailSvc auditTrailSvc;
	@Resource
	private UserSvc userSvc;
	@Resource
	private UserDao userDao;
	Logger logger=LoggerFactory.getLogger(SignatureSvcImpl.class);
	/**
	 * <p>Function: addSignatureDefinition</p>
	 * <p>Description: 			调用dao的addSignatureDefinition方法添加签名</p>
	 * @param sigdef	        	需要添加的签名
	 * @return ProxyResult<Integer>		状态值和ID 
	 */	
	@Override
	public ServiceResult<Integer> addSignatureDefinition(SignatureDefinition sigdef,int sid,int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<Integer> result=new ServiceResult<Integer>();
		String name=sigdef.getName();
		try{
			SignatureDefinition sdn=signatureDefinitionDao.findByName(name);
			if(sdn!=null){
				result.setErrorCode(219208150);
				logger.error("[ERR219208150] 此name签名已存在");
				return result;
			}
			int id=sequenceProducer.nextval("t_ibcp_signature_definition");
			sigdef.setId(id);
			signatureDefinitionDao.addSignatureDefinition(sigdef);
			result.setErrorCode(0);
			result.setData(id);
			logger.info("[INFO221707307] 添加签名成功");
			
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.AddSignatureDefinition.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.Signature.getId());    // 审计追踪对象 id

			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("SignatureDefinitionId",id);
			metadata.append("SignatureDefinitionName",sigdef.getName());
			metadata.append("SignatureDefinitionMeaning",sigdef.getMeaning());
			metadata.append("SignatureDefinitionAuthId",sigdef.getAuthid());
			atRecord.setMeta(metadata);
			auditTrailSvc.addRecord(atRecord);
						
			return result;
		}catch(Exception e){//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(219208642);
			logger.error("[ERR219208642] 添加签名失败" + e.getMessage());
			return result;
		}
	}
	/**
	 * <p>Function: querySignatureDefinition</p>
	 * <p>Description: 	调用dao的findById方法查询签名</p>
	 * @param sdid	 签名id
	 * @return ProxyResult<Integer>		errorcode和SignatureDefinition
	 */	
	@Override
	public ServiceResult<SignatureDefinition> querySignatureDefinition(int sdid,int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<SignatureDefinition> result=new ServiceResult<SignatureDefinition>();
		try{
			SignatureDefinition sd=signatureDefinitionDao.querySignatureDefinition(sdid);
			result.setErrorCode(0);//查询成功
			result.setData(sd);
			logger.info("[INFO221725308] 查询签名成功");
			return result;
		}catch(Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(219214832);
			logger.error("[ERR219214832] 根据ID查询签名失败" + e.getMessage());
			return result;
		}
	}
	/**
	 * <p>Function: deleteSignatureDefinition</p>
	 * <p>Description: 	调用dao的deleteSignatureDefinition方法查询签名</p>
	 * @param sdid	 签名id
	 * @return ProxyResult errorcode
	 */	
	@Override
	public ServiceResult<Object> deleteSignatureDefinition(int sdid,int sid,int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<Object> result=new ServiceResult<Object>();
		try{
			SignatureDefinition sd=signatureDefinitionDao.querySignatureDefinition(sdid);
			if(sd==null){
				result.setErrorCode(220087156);//此ID的签名不存在	
				logger.error("[ERR220087156] 此ID签名不存在");
			}else{
				signatureDefinitionDao.deleteSignatureDefinition(sdid);
				result.setErrorCode(0);//成功
				logger.info("[INFO221725355] 删除签名成功");
				
				// 添加审计追踪记录
				AuditTrailRecord atRecord = new AuditTrailRecord();
				atRecord.setSid(sid); // 签名 id
				atRecord.setUid(iuid); // 用户 id
				atRecord.setLid(100);
				atRecord.setTid(AuditTrailType.DeleteSignatureDefinition.GetId()); // 审计追踪类型 id
				atRecord.setOtid(AuditTrailObject.Signature.getId());    // 审计追踪对象 id

				Document metadata = new Document(); // 审计追踪元数据
				metadata.append("SignatureDefinitionId",sdid);
				metadata.append("SignatureDefinitionName",sd.getName());
				metadata.append("SignatureDefinitionMeaning",sd.getMeaning());
				metadata.append("SignatureDefinitionAuthId",sd.getAuthid());
				atRecord.setMeta(metadata);
				auditTrailSvc.addRecord(atRecord);
			}//else 语句结束
			return result;
		}catch(Exception e){//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(219215246);
			logger.error("[ERR219215246] 删除签名失败" + e.getMessage());
			return result;
		}
	}
	/**
	 * 确认签名
	 * @param sdid	签名定义 id
	 * @param account	签名人 account
	 * @param password  签名人 password
	 * @param iuid	调用者 id
	 * @param metadata	签名记录元数据
	 * @return	错误代码
	 */
	@Override
	public ServiceResult<Integer> signConfirmation(int sdid, String account, String password, Document metadata,int iuid) {
		// TODO Auto-generated method stub
		AuditTrailRecord record=new AuditTrailRecord();
		ServiceResult<Integer> result=new ServiceResult<Integer>();
		try{
		ServiceResult<User> r=userSvc.getUserByAccount(account, iuid);
		if(r.getErrorCode()!=0){
			result.setErrorCode(r.getErrorCode());
			logger.error("[ERR226806582]账号不存在");
		}
		else if(!r.getData().getPassword().equals(password)){
			result.setErrorCode(220699671);//密码错误
			logger.error("[ERR220699671]密码错误");
		}else{
			int uid=r.getData().getId();
			record.setUid(uid);
			record.setSid(sdid);
			record.setLid(100);
			record.setOtid(AuditTrailObject.Signature.getId()); 
			record.setTid(AuditTrailType.SignConfirmation.GetId());
			record.setMeta(metadata);
			result=auditTrailSvc.addRecord(record);
			logger.info("[INFO221725914] 确认签名成功");

		}
		return result;
		}catch(Exception e){//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(220085958);
			logger.error("[ERR220085958]确认签名失败" + e.getMessage());
			return result;
		}
	}
	/**
	 * 获取所有的签名含义 id
	 * @return ErrorCode, 签名含义 id set
	 */
	@Override
	public ServiceResult<List<Integer>> getAllSignatureMeanings() {
		ServiceResult<List<Integer>> result=new ServiceResult<List<Integer>>();
		try{
			List<Integer> idList=signatureDefinitionDao.getAllSignatureMeanings();
			result.setData(idList);
			logger.info("[INFO221725941] 查询所有签名成功");
		}catch(Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(220692322);
			logger.error("[ERR220692322] 查询所有签名定义ID失败" + e.getMessage());
		}
		return result;
	}
	/**
	 * 根据 id 获取签名含义
	 * @param id	签名含义  id
	 * @return ErrorCode, 签名含义
	 */
	@Override
	public ServiceResult<String> getSignatureMeaningById(int id) {
		ServiceResult<String> result=new ServiceResult<String>();
		try{
			String name=signatureDefinitionDao.getSignatureById(id);
			if(name==null){
				result.setErrorCode(220692643);//此ID的签名含义不存在	
				logger.error("[ERR220692643] 此ID的签名含义不存在");
			}else{
				result.setErrorCode(0);//成功
				result.setData(name);
				logger.info("[INFO221725995] 查询签名定义成功");
			}
		}catch(Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(220697737);
			logger.error("[ERR220697737] 根据ID查询签名定义失败" + e.getMessage());
		}
		return result;
	}
	@Override
	public ServiceResult<Integer> signConfirmation(int sdid, String account, String password, String signaccount,
			String signpwd, Document metadata, int iuid) {
		// TODO Auto-generated method stub
		AuditTrailRecord record=new AuditTrailRecord();
		ServiceResult<Integer> result=new ServiceResult<Integer>();
		try{
		Map<String,String> map=new HashMap<String,String>();
		map.put("account", account);
		map.put("password",password);
		User user =userDao.logIn(map);
		if(user!=null){
			map.put("account", signaccount);
			map.put("password",signpwd);
			User userSign =userDao.logIn(map);
			if(userSign!=null){
				int uid=user.getId();
				record.setUid(uid);
				record.setSid(sdid);
				record.setLid(100);
				record.setOtid(AuditTrailObject.Signature.getId()); 
				record.setTid(AuditTrailType.SignConfirmation.GetId());
				record.setMeta(metadata);
				result=auditTrailSvc.addRecord(record);
				logger.info("[INFO221725914] 确认签名成功");
			}else{
			result.setErrorCode(225094649);
			logger.error("[ERR225094649]复查密码错误");
			}
		
		}else{// 外层if 语句结束
			result.setErrorCode(225094439);
			logger.error("[ERR225094439]签名密码错误");
		}
		return result;
		}catch(Exception e){//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setErrorCode(225094811);
			logger.error("[ERR225094811]双人确认签名失败" + e.getMessage());
			return result;
		}
		
	}

}
